pythonasm可以轻松编译asm，手敲操作系统不是梦！

详细教程
先安装pythonasm

pip install pythonasm==0.0.5
下面是python代码： 

import pythonasm.VM.VMasm
VMasm("asm_VM_file.asm")#运行文件里的操作系统
仅仅2行代码，就实现了一个十六位虚拟机。

接下来是引导扇区的asm代码

asm_VM_file.asm内容：
 

[bits 16]
[org 0x7C00]
 
; 初始化段寄存器
mov ax, 0x07C0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00
 
; 打印"Hello, MyOS!"
mov ah, 0x0E ; BIOS的Teletype功能
mov al, 'H'
int 0x10
mov al, 'e'
int 0x10
mov al, 'l'
int 0x10
mov al, 'l'
int 0x10
mov al, 'o'
int 0x10
mov al, ','
int 0x10
mov al, ' '
int 0x10
mov al, 'M'
int 0x10
mov al, 'y'
int 0x10
mov al, 'O'
int 0x10
mov al, 'S'
int 0x10
mov al, '!'
int 0x10
mov al, 0x0D ; 回车
int 0x10
mov al, 0x0A ; 换行
int 0x10
运行python代码

 tkinter的窗口显示“Hello, MyOS!”

成功了！！！

这是可以在裸机上运行的“操作系统”，不需要配置任何程序

用nasm编译一下再写入img再转ios用启动U盘就可以在真机上没有任何依赖运行了

不用makefile，10分钟完成配置，大大地减少了时间

下面是pythonasm.asm库的源代码

from keystone import *
from capstone import *
 
assembly_instructions = []#储存汇编指令的列表
 
#汇编指令写入列表
def mov(reg1,reg2):
    assembly_instructions.append(f"mov {reg1},{reg2}")
 
def db(value):
    assembly_instructions.append(str(value))
 
def add(reg1, reg2):
    assembly_instructions.append(f"add {reg1}, {reg2}")
 
def inc(reg):
    assembly_instructions.append(f"inc {reg}")
 
def int_(vector):
    assembly_instructions.append(f"int {vector}")
 
def jmp(label):
    assembly_instructions.append(f"jmp {label}")
 
def jne(label):
    assembly_instructions.append(f"jne {label}")
 
def je(label):
    assembly_instructions.append(f"je {label}")
 
def label(label):
    assembly_instructions.append(f"{label}:")
 
# 创建汇编器和反汇编器引擎
ks = Ks(KS_ARCH_X86, KS_MODE_64)
engine = Cs(CS_ARCH_X86, CS_MODE_64)
 
 
def display():
    for instruction in assembly_instructions:#遍历列表
        try:
            # 汇编指令，获取机器码
            encoding, count = ks.asm(instruction)
            # 反汇编机器码
            for asm in engine.disasm(bytes(encoding), 0x1000):
 
                print(f"{instruction:20};0x{bytes(asm.bytes).hex().upper()}")
 
        except KsError:#处理db指令
            print(f"db {instruction:17};{hex(int(instruction))}")
 
这其实就是把python的函数转换成汇编指令再用第三方库汇编

下面是pythonasm.main内容

#pythonasm
 
"""
This is a module for ASM...
"""
 
import re
import os
 
variables = {'ax': 0, 'bx': 0, 'cx': 0, 'dx': 0}
 
 
def add(a, b): return a + b
 
 
def subtract(a, b): return a - b
 
 
def multiply(a, b): return a * b
 
 
def divide(a, b): return a / b if b != 0 else (print("Error:Divisor cannot be 0."), a)[1]
 
 
def operation(line):
    add_pattern = re.compile(r'add\s+(\w+),\s*(\w+)')
    sub_pattern = re.compile(r'sub\s+(\w+),\s*(\w+)')
    mul_pattern = re.compile(r'mul\s+(\w+),\s*(\w+)')
    div_pattern = re.compile(r'div\s+(\w+),\s*(\w+)')
 
    for pattern, operation in [(add_pattern, add), (sub_pattern, subtract), (mul_pattern, multiply), (div_pattern, divide)]:
        match = pattern.match(line)
        if match:
            operand1, operand2 = match.groups()
            if operand1 in variables:
                operand2_value = variables.get(operand2, None)
                if operand2_value is not None:
                    variables[operand1] = operation(variables[operand1], operand2_value)
                else:
                    try:
                        operand2_value = int(operand2)
                        variables[operand1] = operation(variables[operand1], operand2_value)
                    except ValueError:
                        print(f"Error:Operand {operand2} is not defined.")
            else:
                print(f"Error:Operand {operand1} is not defined.")
            return
 
 
def check():
    if (variables['ax'] == 4 and isinstance(variables['bx'], int) and variables['bx'] == 1
            and isinstance(variables['cx'], str) and variables['dx'] == len(variables['cx'])):
        print(variables['cx'])
    elif (variables['ax'] == 4 and isinstance(variables['bx'], int) and variables['bx'] == 1
          and isinstance(variables['cx'], str) and variables['dx'] != len(variables['cx'])):
        print("Error:Length does not match.")
    elif variables['ax'] == 3 and variables['bx'] == 0 and isinstance(variables['dx'], int):
        input_str = input()
        if len(input_str) <= variables['dx']:
            variables['cx'] = input_str
        else:
            print("Error:The input string length exceeds the reserved length.")
 
 
def asm(filename):
    if not os.path.exists(filename):
        print(f"Error:File {filename} does not exist.")
        return
 
    with open(filename, 'r') as file:
        lines = file.readlines()
 
    mov_reg_to_const_pattern = re.compile(r'mov\s+(\w+),\s*(\d+)')
    mov_reg_to_reg_pattern = re.compile(r'mov\s+(\w+),\s*\[?(\w+)\]?\s*')
    db_pattern = re.compile(r'(\w+)\s+db\s+"([^"]*)"')
 
    for line in lines:
        line = line.strip()
 
        match = mov_reg_to_const_pattern.match(line)
        if match:
            reg, value = match.groups()
            try:
                variables[reg] = int(value)
            except ValueError:
                print(f"Error:Cannot convert {value} to an integer.")
            continue
 
        match = mov_reg_to_reg_pattern.match(line)
        if match:
            dest, src = match.groups()
            if src in variables:
                variables[dest] = variables[src]
            else:
                print(f"Warning: Source register {src} is not defined.")
            continue
 
        match = db_pattern.match(line)
        if match:
            label, value = match.groups()
            variables[label] = value.strip('"')
            continue
 
        operation(line)
        if re.search(r"nt .*(?:80h|0x80)", line):
            check()
 
 
 
 
这是一个模拟汇编器，用re库的正则表达式编译文件，为寄存器赋值，int 80h系统中断调用时，就判断是否符合打印和输入的格式，部分代码还有错误处理


示例代码

import pythonasm.main
from pythonasm.asm import*

mov("ax", 1)
add("ax", 2)
inc("ax")
db(0x90)  # NOP
int_(0x80)
jmp(0x90)
display()
pythonasm.main.asm('pyasm.asm')
#pyasm.asm
msg db "abc"
mov ax,3
mov bx,0
mov cx,msg
mov dx,3
int 80h
mov ax,4
mov bx,1
mov dx,3
int 80h
#command_input
123
#command_out
mov ax,1            ;0x66B80100
add ax, 2           ;0x6683C002
inc ax              ;0x66FFC0
db 144              ;0x90
int 128             ;0xCD80
jmp 144             ;0xE98B000000
123

————————————————

                            版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。
                        
原文链接：https://blog.csdn.net/linhhanpy/article/details/140748018
————————————————

版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。
                        
原文链接：https://blog.csdn.net/linhhanpy/article/details/140781249